package model

import (
	"fmt"
	pb "gitee.com/enjoy_5/goods-rpc/proto/goods"
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

// 商品表
type Goods struct {
	gorm.Model
	Title       string `gorm:"column:title;type:varchar(255)" json:"title"`
	Point       int64  `gorm:"column:point;type:int(11);comment:积分" json:"point"`
	Description string `gorm:"column:description;type:varchar(255)" json:"description"`
	Img         string `gorm:"column:img;type:varchar(255)" json:"img"`
	TypesID     uint   `gorm:"column:types_id;type:int(11)" json:"types_id"`
}

func (g *Goods) GetGoodsById(Id int64) (info *Goods, err error) {
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Where("id=?", Id).First(&info).Error
	})
	return
}

func (g *Goods) GetGoodsListByPage(page, pageSize int, title string) (goodsList []*Goods, err error) {
	offset := (page - 1) * pageSize
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Where("title like ?", "%"+title+"%").Offset(offset).Limit(pageSize).Find(&goodsList).Error
	})
	return
}

// *
func (g *Goods) GetGoodsList(page, pageSize int) (goodsList []*Goods, err error) {
	offset := (page - 1) * pageSize
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Offset(offset).Limit(pageSize).Find(&goodsList).Error
	})
	return
}

// 多个商品查询  *
func (g *Goods) GetGoodsInfoByIds(ids []int64) (info []Goods, err error) {
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(g).Where("id in(?)", ids).Find(&info).Error
	})
	return
}

func (g *Goods) GoodList(page, pageSize int, typeID int64, title string) (goodInfo []*pb.GoodListInfo, err error) {
	// 分页参数校验
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}

	var ids []int64
	res := make(map[int64]*pb.GoodListInfo)

	// 查询商品信息
	var goodsList []*Goods
	err = mysql.WithMysql(func(db *gorm.DB) error {
		db = db.Model(g)
		if typeID == 0 {
			return db.Find(&goodsList).Error
		}
		if typeID != 0 {
			db = db.Where("types_id = ?", typeID) // 修正字段名
		}
		if title != "" {
			db = db.Where("title LIKE ?", "%"+title+"%")
		}
		return db.Offset((page - 1) * pageSize).
			Limit(pageSize).
			Find(&goodsList).Error
	})
	if err != nil {
		return nil, fmt.Errorf("查询商品失败: %v", err)
	}

	for _, val := range goodsList {
		id := int64(val.ID)
		ids = append(ids, id)
		res[id] = &pb.GoodListInfo{
			Title: val.Title,
			Img:   val.Img,
			ID:    int64(val.ID),
		}
	}
	//查询商品属性价格
	var goodsSkuList []*GoodsSku
	err = mysql.WithMysql(func(db *gorm.DB) error {
		return db.Where("id in(?)", ids).Find(&goodsSkuList).Error
	})
	// 将商品属性价格信息合并到对应的商品信息中
	for _, val := range goodsSkuList {
		goodsID := val.GoodsId
		if info, ok := res[goodsID]; ok {
			info.Price = float32(val.Price)
			info.VipPrice = float32(val.VipPrice)
			info.ID = goodsID
		}
	}
	// 将映射中的商品信息转换为切片
	for _, info := range res {
		goodInfo = append(goodInfo, info)
	}
	return
}
